package com.jin.pattern.singleton;

/**
 * 单例模式(Singleton)
 * 懒汉式，时间换空间，线程非安全，无法确保单例
 * @author Jin
 * @datetime 2015/1/10 下午2:44:41
 */
public class Singleton1 {

	private static Singleton1 INSTANCE = null;
	
	private Singleton1(){
	}
	
	public static Singleton1 getInstance(){
		if(INSTANCE == null){
			INSTANCE = new Singleton1();
		}
		return INSTANCE;
	}
}

/**
 * 单例模式(Singleton)
 * 加同步锁解决了线程安全问题，但是如果调用频繁，性能较低
 * @author Jin
 * @datetime 2015/1/10 下午2:44:41
 */
class Singleton2 {
	
	private static Singleton2 INSTANCE = null;
	
	private Singleton2(){
	}
	
	public synchronized static Singleton2 getInstance(){
		if(INSTANCE == null){
			INSTANCE = new Singleton2();
		}
		return INSTANCE;
	}
}

/**
 * 单例模式(Singleton)
 * 双重检查加锁，用volatile修饰变量，使变量不被线程缓存
 * 由于new Singleton3()在不同JVM上有不同表现，也不能确保DCL（double checked locking）的线程安全性
 * @author Jin
 * @datetime 2015/1/10 下午2:44:41
 */
class Singleton3 {
	
	private volatile static Singleton3 INSTANCE = null;
	
	private Singleton3(){
	}
	
	public static Singleton3 getInstance(){
		if(INSTANCE == null){
			synchronized (INSTANCE) {
				if(INSTANCE == null){
					INSTANCE = new Singleton3();
				}
			}
		}
		return INSTANCE;
	}
}
